package com.jhgsys.internal.system.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jhgsys.internal.common.authentication.ShiroHelper;
import com.jhgsys.internal.common.constant.DictCodeConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.entity.DictItem;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.system.dto.*;
import com.jhgsys.internal.system.entity.*;
import com.jhgsys.internal.system.service.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.ExpiredSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author MrBird
 */
@Controller("systemView")
public class ViewController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ViewController.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private ShiroHelper shiroHelper;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IMenuService menuService;

    /**
     * 岗位
     */
    @Autowired
    private IPostService postService;

    @GetMapping("login")
    @ResponseBody
    public Object login(HttpServletRequest request) {
        if (FebsUtil.isAjaxRequest(request)) {
            request.getSession().invalidate();
            throw new ExpiredSessionException();
        } else {
            ModelAndView mav = new ModelAndView();
            mav.setViewName(FebsUtil.view("login"));
            return mav;
        }
    }

    @GetMapping("unauthorized")
    public String unauthorized() {
        return FebsUtil.view("error/403");
    }



    @GetMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @GetMapping("index")
    public String     index(Model model,HttpServletRequest requset, HttpServletResponse  response) throws Exception{
        AuthorizationInfo authorizationInfo = shiroHelper.getCurrentuserAuthorizationInfo();
        User user = super.getCurrentUser();
        //user.setPassword("It's a secret");
        model.addAttribute("user", userService.findByName(user.getUserName())); // 获取实时的用户信息
        model.addAttribute("permissions", authorizationInfo.getStringPermissions());
        model.addAttribute("roles",authorizationInfo.getRoles());
         return "index";
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "layout")
    public String layout() {
        return FebsUtil.view("layout");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "password/update")
    public String passwordUpdate() {
        return FebsUtil.view("system/user/passwordUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/notice")
    public String systemNotice() {
        return FebsUtil.view("system/user/notice");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile")
    public String userProfile() {
        return FebsUtil.view("system/user/userProfile");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/avatar")
    public String userAvatar() {
        return FebsUtil.view("system/user/avatar");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile/update")
    public String profileUpdate(Model model) {
        model.addAttribute("contractorList",getBaseContractors(getCurrentTenantId()));
        resolveUserModelByUserId(getCurrentUserId(), model, false);
        return FebsUtil.view("system/user/profileUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user")
    @RequiresPermissions("user:view")
    public String systemUser(Model model) {
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("system/user/orgUser");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/webuser")
    @RequiresPermissions("webuser:view")
    public String systemWebUser(Model model) {
        return FebsUtil.view("system/user/webUser");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/webuser/add")
    @RequiresPermissions("webuser:view")
    public String systemWebUserAdd(Model model) {
        return FebsUtil.view("system/user/webUserAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/webuser/update/{userName}")
    @RequiresPermissions("webuser:view")
    public String systemWebUserUpdate(Model model, @PathVariable String userName) {
        resolveUserModel(userName, model, false);
        return FebsUtil.view("system/user/webUserUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/ftauser")
    @RequiresPermissions("ftauser:view")
    public String systemFtaUser(Model model) {
        return FebsUtil.view("system/user/ftaUser");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/ftauser/add")
    @RequiresPermissions("ftauser:view")
    public String systemFtaUserAdd(Model model) {
        return FebsUtil.view("system/user/ftaUserAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/ftauser/update/{userName}")
    @RequiresPermissions("ftauser:view")
    public String systemFtaUserUpdate(Model model, @PathVariable String userName) {
        resolveUserModel(userName, model, false);
        return FebsUtil.view("system/user/ftaUserUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/add/{deptTenantId}")
    @RequiresPermissions("user:add")
    public String systemUserAdd(Model model, @PathVariable String deptTenantId) {
        Role role = new Role() ;
        role.setTenantId(deptTenantId);
        List<Role> roleList = roleService.findRoles(role);
        model.addAttribute("roleList",roleList);
        model.addAttribute("postList",getPostByTenantId(deptTenantId));
        model.addAttribute("contractorList",getBaseContractors(deptTenantId));
        return FebsUtil.view("system/user/userAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/detail/{userName}")
    @RequiresPermissions("user:view")
    public String systemUserDetail(@PathVariable String userName, Model model) {
        resolveUserModel(userName, model, true);
        return FebsUtil.view("system/user/userDetail");
    }

    @GetMapping(value = FebsConstant.VIEW_PREFIX + "system/user/update/{userId}")
    @RequiresPermissions("user:update")
    public String systemUserUpdate(@PathVariable String userId, Model model) {
        model.addAttribute("utype", getCurrentUserType());
        model.addAttribute("contractorList",getBaseContractors(getCurrentTenantId()));
        resolveUserModelByUserId(userId, model, false);
        return FebsUtil.view("system/user/userUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/role")
    @RequiresPermissions("role:view")
    public String systemRole(Model model) {
        //查询用户对应所属公司
        TenantDto tenant = tenantService.findTenantByTenantId(getCurrentUser().getTenantId());

        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenant", tenant);
        List<DictItem> dictItems = dictService.findDictByCode(DictCodeConstant.SYSTEM_ROLE_TYPE);
        if(CollectionUtils.isNotEmpty(dictItems)){
            model.addAttribute("roleTypeList",dictItems);
        }
        return FebsUtil.view("system/role/role");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/role/add")
    @RequiresPermissions("role:view")
    public String systemRoleAdd(Model model) {
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        return FebsUtil.view("system/role/roleEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/role/update/{id}")
    @RequiresPermissions("role:view")
    public String systemRoleUpdate(Model model, @PathVariable("id") String id) {
        RoleDto role = roleService.findRoleByRoleId(id);
        model.addAttribute("role", role);
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", role.getTenantId());
        model.addAttribute("utype", getCurrentUserType());
        return FebsUtil.view("system/role/roleEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/tenant")
    @RequiresPermissions("tenant:view")
    public String systemTenant(Model model) {
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("system/tenant/tenant");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/tenant/add")
    @RequiresPermissions("tenant:view")
    public String systemTenantAdd(Model model) {
        model.addAttribute("tenant", new Tenant());
        model.addAttribute("tenantSelect",tenantService.findTenantDict(new Tenant(),""));
        //设置数据字典
        setModelDict(model);
        return FebsUtil.view("system/tenant/tenantEditTab");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/tenant/update/{id}")
    @RequiresPermissions("tenant:view")
    public String systemTenantUpdate(Model model, @PathVariable("id") String id) {
        TenantDto tenantDto = tenantService.findTenantByTenantId(id);
        model.addAttribute("tenant", tenantDto);
        model.addAttribute("tenantSelect", tenantService.findTenantDict(new Tenant(),id));
        //设置数据字典
        setModelDict(model);
        return FebsUtil.view("system/tenant/tenantEditTab");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/tenant/detail/{id}")
    @RequiresPermissions("tenant:view")
    public String systemTenantDetail(Model model, @PathVariable("id") String id) {
        TenantDto tenantDto = tenantService.findTenantByTenantId(id);
        model.addAttribute("tenant", tenantDto);
        return FebsUtil.view("system/tenant/tenantDetail");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menu")
    @RequiresPermissions("menu:view")
    public String systemMenu() {
        return FebsUtil.view("system/menu/menu");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menuList")
    @RequiresPermissions("menu:view")
    public String systemMenuList() {
        return FebsUtil.view("system/menu/menuList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menu/add")
    @RequiresPermissions("menu:view")
    public String systemMenuAdd() {
        return FebsUtil.view("system/menu/menuEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menu/update/{menuId}")
    @RequiresPermissions("menu:view")
    public String systemMenuUpdate(Model model,@PathVariable("menuId") String menuId) {
        MenuDto menu = menuService.findMenuById(menuId);
        model.addAttribute("menu",menu);
        return FebsUtil.view("system/menu/menuEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/dept")
    @RequiresPermissions("dept:view")
    public String systemDept(Model model) {
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("tenantList",getTenantList());
        return FebsUtil.view("system/dept/dept");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/deptList")
    @RequiresPermissions("dept:view")
    public String systemDeptList(Model model) {
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("tenantList",getTenantList());
        return FebsUtil.view("system/dept/deptList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/dept/addDept")
    @RequiresPermissions("dept:view")
    public String deptAddNew() {
        return FebsUtil.view("system/dept/deptEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/dept/updateDept/{id}")
    @RequiresPermissions("dept:view")
    public String deptEditNew(Model model, @PathVariable("id") String id) {
        Dept dept = deptService.findDeptByDeptId(id);
        model.addAttribute("dept", dept);
        return FebsUtil.view("system/dept/deptEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "dept/add")
    @RequiresPermissions("dept:view")
    public String deptAdd() {
        return FebsUtil.view("system/dept/edit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "dept/update/{id}")
    @RequiresPermissions("dept:view")
    public String deptEdit(Model model, @PathVariable("id") String id) {
        Dept dept = deptService.findDeptByDeptId(id);
        model.addAttribute("dept", dept);
        return FebsUtil.view("system/dept/edit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/post")
    @RequiresPermissions("post:view")
    public String systemPost(Model model) {
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("system/post/post");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/post/add")
    @RequiresPermissions("post:add")
    public String systemPostAdd(Model model) {
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("system/post/postEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/post/update/{postId}")
    @RequiresPermissions("post:update")
    public String systemPostUpdate(Model model, @PathVariable("postId") String postId) {
        PostDto postDto = postService.findDtoById(postId);
        model.addAttribute("post", postDto);
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("system/post/postEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/post/detail/{postId}")
    @RequiresPermissions("post:view")
    public String systemPostDetail(Model model, @PathVariable("postId") String postId) {
        model.addAttribute("utype", getCurrentUserType());
        return FebsUtil.view("system/post/postDetail");
    }


    @RequestMapping(FebsConstant.VIEW_PREFIX + "index")
    public String pageIndex() {
        return FebsUtil.view("index");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "404")
    public String error404() {
        return FebsUtil.view("error/404");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "403")
    public String error403() {
        return FebsUtil.view("error/403");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "500")
    public String error500() {
        return FebsUtil.view("error/500");
    }

    private void resolveUserModel(String userName, Model model, Boolean transform) {
        User user = userService.findByName(userName);
        model.addAttribute("user", user);
        if (transform && null != user) {
            String ssex = user.getSex();
            if (User.SEX_MALE.equals(ssex)) {
                user.setSex("男");
            } else if (User.SEX_FEMALE.equals(ssex)) {
                user.setSex("女");
            } else {
                user.setSex("保密");
            }
        }
        if ( null != user &&  null != user.getLastLoginTime()) {
            model.addAttribute("lastLoginTime", DateUtil.getDateFormat(user.getLastLoginTime(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
    }

    private void resolveUserModelByUserId(String userId, Model model, Boolean transform) {
        User user = userService.findById(userId);
        if(null != user){
            Dept dept = deptService.findDeptByDeptId(user.getDeptId());
            if(null != dept){
                user.setDeptName(dept.getDeptName());
            }
        }
        UserDto userDto = BeanHelper.copyProperties(user,UserDto.class);
        TenantDto tenantByTenantId = tenantService.findTenantByTenantId(userDto.getTenantId());
        if(null != tenantByTenantId){
            userDto.setTenantName(tenantByTenantId.getTenantName());
            List<Post> postList = getPostByTenantId(tenantByTenantId.getTenantId());
            model.addAttribute("postList", postList);
        }
        model.addAttribute("user", userDto);
        if (transform && null != user) {
            String ssex = user.getSex();
            if (User.SEX_MALE.equals(ssex)) {
                user.setSex("男");
            } else if (User.SEX_FEMALE.equals(ssex)) {
                user.setSex("女");
            } else {
                user.setSex("保密");
            }
        }
        if ( null != user &&  null != user.getLastLoginTime()) {
            model.addAttribute("lastLoginTime", DateUtil.getDateFormat(user.getLastLoginTime(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
    }
}
